package helpers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;

public class CacheHelper {
	public static StringBuffer getCachedFile(String url) throws Exception {
		// Replace the url's slashes with dashes so that it can be written to
		// the disk
		// and put it in the tmp-cache directory
		File urlCache = new File( "tmp-cache/" + url.replace( '/', '-' ) );
		
		// Create the directory to put the file
		new File( "tmp-cache/" ).mkdir();

		if ( urlCache.exists() ) {
			// The file is already cached just read it and return it
			BufferedReader in = new BufferedReader( new FileReader( urlCache ) );

			StringBuffer buffer = new StringBuffer();

			String input;

			while ( (input = in.readLine()) != null ) {
				buffer.append( input + "\n" );
			}

			in.close();

			return buffer;
		} else {
			// The file is not cached, get it, save it, return it
			// Create a URL for the desired page
			URL url2 = new URL( url.replace( " ", "%20" ) );

			// Read all the text returned by the server
			BufferedReader in = new BufferedReader( new InputStreamReader( url2
					.openStream() ) );

			// Write it all out to a file and the new buffer
			BufferedWriter cacheWriter = new BufferedWriter( new FileWriter(
					urlCache ) );

			StringBuffer buffer = new StringBuffer();
			String input;

			while ( (input = in.readLine()) != null ) {
				buffer.append( input + "\n" );
				cacheWriter.write( input + "\n" );
			}

			cacheWriter.close();
			in.close();

			return buffer;
		}
	}
}
